package com.xgimi.locales.ext

import java.util.regex.Pattern

//简单错误校验
private val sPattern = mapOf(
    "(% [sS])|(%S)" to "%s",
    "(% [dD])|(%D)" to "%d",
    "(% [fF])|(%F)" to "%f",
)
//特殊-例如阿拉伯语需要对s%做反转
private val sPatternSpacial = mapOf(
    "(٪ [sS])|(٪[sS])|(%s)" to "s%",
    "(٪ [dD])|(٪[dD])|(%d)" to "d%",
    "(٪ [fF])|(٪[fF])|(%f)" to "f%",
)
//是否需要用CDATA
private val isNeedCdataPattern = "<\\/?.+?>"
private val isCdataPattern = "^<!\\[CDATA\\[.+]]>\$"

//格式化 % s % d 异常字符
fun String.stringChartFormat(langType: String): String {
    var temp = this
    sPattern.forEach {
        temp = Pattern.compile(it.key).matcher(temp).replaceAll(it.value)
    }
    if (langType in arrayOf("ar", "iw")) {
        sPatternSpacial.forEach {
            temp = Pattern.compile(it.key).matcher(temp).replaceAll(it.value)
        }
    }
    // 转义符号替换<![CDATA[ ]]>
    val find = Pattern.compile(isNeedCdataPattern).matcher(temp).find()
    val isCData = Pattern.compile(isCdataPattern).matcher(temp).find()
    if (find && !isCData) {
        temp = "<![CDATA[$temp]]>"
    }
    // 转义字符串 比如 "&" -> &amp;  ' -> \'
    return temp
}